/**
 * @(#)ApkConfigController.java 2017年03月1日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.action;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.jsbd.boss.domian.Book;
import org.jsbd.boss.domian.BookMark;
import org.jsbd.boss.domian.BookMarkFailCount;
import org.jsbd.boss.domian.channel.BaseResultVo;
import org.jsbd.boss.enums.ResponseEnum;
import org.jsbd.boss.service.IBookMarkService;
import org.jsbd.boss.util.PropertiesUtil;
import org.jsbd.boss.annotation.SystemControllerLog;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ExportExcel;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.ResponseUtils;
import org.jsbd.boss.common.ReturnJsonCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/bookMark")
public class BookMarkController {

	public static final Logger logger = LoggerFactory.getLogger(BookMarkController.class);
	public static final String EXCEL_NAME = "mark书籍失败次数.xlsx";

	@Autowired
	private IBookMarkService bookMarkService;

	@RequestMapping(value = "list", method = RequestMethod.GET)
	public String list(Model model) {
		return "bookMark/list";
	}

	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(BookMark bookMark) {
		if (StringUtils.isBlank(bookMark.getMark())) {
			return ResponseMapUtils.responseFail("mark不能为空");
		}
		bookMarkService.save(bookMark);
		return ResponseMapUtils.responseSuccess();
	}

	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public Object update(BookMark bookMark) {
		if (bookMark.getId() == null) {
			return ResponseMapUtils.responseFail("参数缺失，请确认参数再提交");
		}
		BookMark obj = bookMarkService.getById(bookMark.getId());
		obj.setBookCompanyId(bookMark.getBookCompanyId());
		obj.setMark(bookMark.getMark());
		obj.setApkName(bookMark.getApkName());
		obj.setStatus(bookMark.getStatus());
		bookMarkService.update(obj);
		return ResponseMapUtils.responseSuccess();
	}

	@RequestMapping(value = "getListPage")
	@ResponseBody
	public Map<String, Object> getListPage(DataGridModel page, BookMark bookMark) throws Exception {
		String mark = bookMark.getMark();
		if (org.apache.commons.lang.StringUtils.isNotBlank(mark)) {
			String[] marks = mark.split(" ");
			List<String> keywords = new ArrayList<>();
			for (String keyword : marks) {
				keywords.add(keyword);
			}
			bookMark.setKeywords(keywords);
		}
		return bookMarkService.getListPage(page, bookMark);
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public void delete(Integer[] ids, HttpServletResponse response) {
		try {
			List<Integer> list = Arrays.asList(ids);
			bookMarkService.delete(list);
			ResponseUtils.responseSuccess(response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			ResponseUtils.responseFailure(response);
		}
	}

	@RequestMapping(value = "apkName")
	public void getApkName(String mark, HttpServletResponse response) {
		BaseResultVo resultVo = new BaseResultVo();
		try {
			String apkName = bookMarkService.getApkNameByMark(mark);
			resultVo.setData(apkName == null ? "" : apkName);
			resultVo.setMessage(ResponseEnum.SUCC.getDesc());
			resultVo.setStatus(ResponseEnum.SUCC.getStatus());

		} catch (Exception e) {
			logger.error("获取apkName出错", e);
			resultVo.setMessage(ResponseEnum.ERROR.getDesc());
			resultVo.setStatus(ResponseEnum.ERROR.getStatus());
		}
		ResponseUtils.renderJson(response, resultVo.toString());
	}

	@RequestMapping(value = "getFailCountListPage")
	@ResponseBody
	public Map<String, Object> getFailCountListPage(DataGridModel page, BookMarkFailCount bookMarkFailCount) throws Exception {
		return bookMarkService.getFailCountListPage(page, bookMarkFailCount);
	}
	
	@RequestMapping(value = "/exportFailCount", method = RequestMethod.POST)
	@SystemControllerLog(description = "导出excel")
	@ResponseBody
	public void exportExcel(BookMarkFailCount bookMarkFailCount, HttpServletResponse response) throws Exception {
		List<BookMarkFailCount> list = bookMarkService.getFailCountList(bookMarkFailCount);
		Integer total = list.size();

		JSONObject resultJson = new JSONObject();
		if (total == 0) {
			resultJson.put(ReturnJsonCode.RETURN_CODE, ReturnJsonCode.MsgCodeEnum.EXCEL_EXPORT_ERROR.getCode());
			resultJson.put(ReturnJsonCode.RETURN_MSG, "操作失败！该范围内没有数据。");
			ResponseUtils.renderJson(response, resultJson.toString());
			return;
		}
		String size = PropertiesUtil.getValue("excel_max_size");
		if (total > Integer.parseInt(size)) {
			resultJson.put(ReturnJsonCode.RETURN_CODE, ReturnJsonCode.MsgCodeEnum.EXCEL_EXPORT_ERROR.getCode());
			resultJson.put(ReturnJsonCode.RETURN_MSG, "操作失败！查询数据超过excel可导出上限。");
			ResponseUtils.renderJson(response, resultJson.toString());
			return;
		}

		response.setContentType("octets/stream");
		response.addHeader("Content-Disposition",
				"attachment;filename=" + new String(EXCEL_NAME.getBytes("gb2312"), "iso8859-1"));

		ExportExcel<BookMarkFailCount> excel = new ExportExcel<BookMarkFailCount>();
		String[] headers = { "mark", "书名 ", "失败次数"};
		OutputStream out = response.getOutputStream();

		excel.exportExcel(EXCEL_NAME, headers, list, out, "yyyy-MM-dd");

		out.close();
	}
}
